home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / HTTPRESPONSE.PY < prev    next >
Encoding:
Python Source  |  2000-09-15  |  14.6 KB  |  400 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """
  65. ZServer HTTPResponse
  66.  
  67. The HTTPResponse class takes care of server headers, response munging
  68. and logging duties.
  69.  
  70. """
  71. import time, regex, string, sys, tempfile
  72. from cStringIO import StringIO
  73. import thread
  74. from ZPublisher.HTTPResponse import HTTPResponse, end_of_header_search
  75. from medusa.http_date import build_http_date
  76. from PubCore.ZEvent import Wakeup
  77. from medusa.producers import hooked_producer
  78. from medusa import http_server, asyncore
  79. from Producers import ShutdownProducer, LoggingProducer, CallbackProducer, \
  80.     file_part_producer, file_close_producer
  81. from types import LongType
  82. import DebugLogger
  83.  
  84.  
  85. class ZServerHTTPResponse(HTTPResponse):
  86.     "Used to push data into a channel's producer fifo"
  87.  
  88.     # Set this value to 1 if streaming output in
  89.     # HTTP/1.1 should use chunked encoding
  90.     http_chunk=1
  91.     http_chunk_size=1024
  92.     
  93.     # defaults
  94.     _http_version='1.0'
  95.     _http_connection='close'
  96.     _server_version='Zope/2.0 ZServer/2.0'
  97.  
  98.     # using streaming response
  99.     _streaming=0
  100.     # using chunking transfer-encoding
  101.     _chunking=0 
  102.     
  103.     def __str__(self,
  104.                 html_search=regex.compile('<html>',regex.casefold).search,
  105.                 ):        
  106.         if self._wrote:
  107.             if self._chunking:
  108.                 return '0\r\n\r\n'
  109.             else:
  110.                 return ''
  111.  
  112.         headers=self.headers
  113.         body=self.body
  114.         if body:
  115.             isHTML=contHTML=self.isHTML(body)
  116.             if not headers.has_key('content-type'):
  117.                 if isHTML:
  118.                     c='text/html'
  119.                 else:
  120.                     c='text/plain'
  121.                 self.setHeader('content-type',c)
  122.             else:
  123.                 isHTML = string.split(headers.get('content-type', ''),
  124.                                       ';')[0] == 'text/html'
  125.  
  126.             if isHTML and end_of_header_search(self.body) < 0:
  127.                 lhtml=html_search(body)
  128.                 if lhtml >= 0:
  129.                     lhtml=lhtml+6
  130.                     body='%s<head></head>\n%s' % (body[:lhtml],body[lhtml:])
  131.                 elif contHTML:
  132.                     body='<html><head></head>\n' + body
  133.                 else:
  134.                     body='<html><head></head>\n' + body + '\n</html>\n'
  135.                 self.setBody(body)
  136.                 body=self.body
  137.  
  138.         # set 204 (no content) status if 200 and response is empty
  139.         # and not streaming
  140.         if not headers.has_key('content-type') and \
  141.                 not headers.has_key('content-length') and \
  142.                 not self._streaming and \
  143.                 self.status == 200:
  144.             self.setStatus('nocontent')
  145.  
  146.         # add content length if not streaming
  147.         if not headers.has_key('content-length') and \
  148.                 not self._streaming:
  149.             self.setHeader('content-length',len(body))
  150.  
  151.         # ugh - str(content-length) could be a Python long, which will
  152.         # produce a trailing 'L' :( This can go away when we move to
  153.         # Python 2.0...
  154.         content_length= headers.get('content-length', None)
  155.         if type(content_length) is LongType:
  156.             str_rep=str(content_length)
  157.             if str_rep[-1:]=='L':
  158.                 str_rep=str_rep[:-1]
  159.                 self.setHeader('content-length', str_rep)
  160.  
  161.         headersl=[]
  162.         append=headersl.append
  163.      
  164.         status=headers.get('status', '200 OK')
  165.      
  166.         # status header must come first.
  167.         append("HTTP/%s %s" % (self._http_version or '1.0' , status))
  168.         if headers.has_key('status'):
  169.             del headers['status']
  170.         
  171.         # add zserver headers
  172.         append('Server: %s' % self._server_version) 
  173.         append('Date: %s' % build_http_date(time.time()))
  174.  
  175.         if self._http_version=='1.0':
  176.             if self._http_connection=='keep-alive' and \
  177.                     self.headers.has_key('content-length'):
  178.                 self.setHeader('Connection','Keep-Alive')
  179.             else:
  180.                 self.setHeader('Connection','close')
  181.                 
  182.         # Close the connection if we have been asked to.
  183.         # Use chunking if streaming output.
  184.         if self._http_version=='1.1':
  185.             if self._http_connection=='close':
  186.                 self.setHeader('Connection','close')
  187.             elif not self.headers.has_key('content-length'):
  188.                 if self.http_chunk and self._streaming:
  189.                     self.setHeader('Transfer-Encoding','chunked')
  190.                     self._chunking=1
  191.                 else:
  192.                     self.setHeader('Connection','close')                
  193.         
  194.         for key, val in headers.items():
  195.             if string.lower(key)==key:
  196.                 # only change non-literal header names
  197.                 key="%s%s" % (string.upper(key[:1]), key[1:])
  198.                 start=0
  199.                 l=string.find(key,'-',start)
  200.                 while l >= start:
  201.                     key="%s-%s%s" % (key[:l],string.upper(key[l+1:l+2]),key[l+2:])
  202.                     start=l+1
  203.                     l=string.find(key,'-',start)
  204.             append("%s: %s" % (key, val))
  205.         if self.cookies:
  206.             headersl=headersl+self._cookie_list()
  207.         headersl[len(headersl):]=[self.accumulated_headers, body]
  208.         return string.join(headersl,'\r\n')
  209.  
  210.     _tempfile=None
  211.     _templock=None
  212.     _tempstart=0
  213.     
  214.     def write(self,data):
  215.         """\
  216.         Return data as a stream
  217.  
  218.         HTML data may be returned using a stream-oriented interface.
  219.         This allows the browser to display partial results while
  220.         computation of a response to proceed.
  221.  
  222.         The published object should first set any output headers or
  223.         cookies on the response object.
  224.  
  225.         Note that published objects must not generate any errors
  226.         after beginning stream-oriented output. 
  227.  
  228.         """
  229.         stdout=self.stdout
  230.         
  231.         if not self._wrote:
  232.             l=self.headers.get('content-length', None)
  233.             if l is not None:
  234.                 try:
  235.                     if type(l) is type(''): l=string.atoi(l)
  236.                     if l > 128000:
  237.                         self._tempfile=tempfile.TemporaryFile()
  238.                         self._templock=thread.allocate_lock()
  239.                 except: pass
  240.  
  241.             self._streaming=1
  242.             stdout.write(str(self))
  243.             self._wrote=1
  244.  
  245.         if not data: return
  246.  
  247.         if self._chunking:
  248.             data = '%x\r\n%s\r\n' % (len(data),data)
  249.  
  250.         t=self._tempfile
  251.         if t is None:
  252.             stdout.write(data)
  253.         else:
  254.             l=len(data)
  255.             b=self._tempstart
  256.             e=b+l
  257.             self._templock.acquire()
  258.             try:
  259.                 t.seek(b)
  260.                 t.write(data)
  261.             finally:
  262.                 self._templock.release()
  263.             self._tempstart=e
  264.             stdout.write(file_part_producer(t,self._templock,b,e), l)
  265.     
  266.     def _finish(self):
  267.         stdout=self.stdout
  268.  
  269.         t=self._tempfile
  270.         if t is not None:
  271.             stdout.write(file_close_producer(t), 0)
  272.             self._tempfile=None
  273.         
  274.         stdout.finish(self)
  275.         stdout.close()
  276.         
  277.         self.stdout=None # need to break cycle?
  278.         self._request=None
  279.  
  280.  
  281. class ChannelPipe:
  282.     """Experimental pipe from ZPublisher to a ZServer Channel.
  283.     Should only be used by one thread at a time. Note also that
  284.     the channel will be being handled by another thread, thus
  285.     restrict access to channel to the push method only."""
  286.  
  287.     def __init__(self, request):
  288.         self._channel=request.channel
  289.         self._request=request
  290.         self._shutdown=0
  291.         self._close=0
  292.         self._bytes=0
  293.     
  294.     def write(self, text, l=None):
  295.         if self._channel.closed:
  296.             return
  297.         if l is None: l=len(text)
  298.         self._bytes=self._bytes + l
  299.         self._channel.push(text,0)
  300.         Wakeup()
  301.         
  302.     def close(self):
  303.         DebugLogger.log('A', id(self._request), 
  304.                 '%s %s' % (self._request.reply_code, self._bytes))
  305.         if not self._channel.closed:
  306.             self._channel.push(LoggingProducer(self._request, self._bytes), 0)
  307.             self._channel.push(CallbackProducer(self._channel.done), 0)
  308.             self._channel.push(CallbackProducer(
  309.                 lambda t=('E', id(self._request)): apply(DebugLogger.log, t)), 0)
  310.             if self._shutdown:
  311.                 try: r=self._shutdown[0]
  312.                 except: r=0
  313.                 sys.ZServerExitCode=r
  314.                 self._channel.push(ShutdownProducer(), 0)
  315.                 Wakeup()
  316.             else:
  317.                 if self._close: self._channel.push(None, 0)
  318.             Wakeup()
  319.         else:
  320.             # channel closed too soon
  321.  
  322.             self._request.log(self._bytes)
  323.             DebugLogger.log('E', id(self._request))
  324.  
  325.             if self._shutdown:
  326.                 try: r=self._shutdown[0]
  327.                 except: r=0
  328.                 sys.ZServerExitCode=r
  329.                 Wakeup(lambda: asyncore.close_all())
  330.             else:
  331.                 Wakeup()
  332.  
  333.         self._channel=None #need to break cycles?
  334.         self._request=None
  335.  
  336.     def flush(self): pass # yeah, whatever
  337.     
  338.     def finish(self, response):
  339.         if response.headers.get('bobo-exception-type', '') == \
  340.                 'exceptions.SystemExit':
  341.  
  342.             r=response.headers.get('bobo-exception-value','0')
  343.             try: r=string.atoi(r)
  344.             except: r = r and 1 or 0
  345.             self._shutdown=r,
  346.         if response.headers.get('connection','') == 'close' or \
  347.                 response.headers.get('Connection','') == 'close':
  348.             self._close=1
  349.         self._request.reply_code=response.status
  350.         
  351.     def retry(self):
  352.         """Return a request object to be used in a retry attempt
  353.         """
  354.         
  355.         # This implementation is a bit lame, because it assumes that
  356.         # only stdout stderr were passed to the constructor. OTOH, I
  357.         # think that that's all that is ever passed.
  358.  
  359.         response=self.__class__(stdout=self.stdout, stderr=self.stderr)
  360.         response._http_version=self._http_version
  361.         response._http_connection=self._http_connection
  362.         response._server_version=self._server_version
  363.         return response
  364.         
  365.     
  366.         
  367. def make_response(request, headers):
  368.     "Simple http response factory"
  369.     # should this be integrated into the HTTPResponse constructor?
  370.     
  371.     response=ZServerHTTPResponse(stdout=ChannelPipe(request), stderr=StringIO())
  372.     response._http_version=request.version
  373.     response._http_connection=string.lower(
  374.             http_server.get_header(http_server.CONNECTION, request.header))
  375.     response._server_version=request.channel.server.SERVER_IDENT
  376.     return response
  377.     
  378.  
  379.